const process = require('process');
//1. 连接数据库
require('./connect/connect.js');
//2. 定义骨架
// const { userSchema } = require('./schema/index.js');
//3. 定义模型
const { usersModel, positionModel } = require('./model/index.js');




//4. 实例化得到实体


const Mongo = {
    position: { //职位的增删改查
        async add(data) {
            let position = new positionModel(data);
            let flag = true;

            await positionModel.find((err, res) => {
                if (!err && res) {
                    res.forEach((val) => {
                        if (val.companyName === data.companyName && val.positionName === data.positionName) {
                            flag = false;
                            return flag;
                        }
                    });
                    if (flag) {
                        position.save();
                    }
                }
            });
            return flag;
        },
        find() {
            // let position = new positionModel(data);
            let promise = positionModel.find({}).then(res => res);
            return promise;
        },
        remove({ id, companyLogo }) {
            let p1 = positionModel.findById(id, (err, res) => {
                if (!err && res) {
                    res.remove();
                    console.log('remove this position success!');
                    return;
                }
            }).then(flag => {
                if (flag) { return true } else { return false }
            }).catch(flag => false);
            return p1;
        }
    },


    //增删改查
    user: {
        async signup({ username, password }) {
            const user = new usersModel();
            let flag = true;
            user.username = username;
            user.password = password;
            //如果数据库中已经存在这个名字，那么我们就不在入库了
            await usersModel.find({}, function(err, res) {
                res.forEach(function(ele) {
                    if (ele.username === username) {
                        flag = false;
                        return;
                    }
                })
                if (flag) {
                    user.save(function(err) {
                        if (!err) {
                            console.log('add  succ')
                        }
                    })
                }
            });
            return flag;
        },
        async signin({ username, password }) {
            let flag = false;
            //如果数据库中已经存在这个名字，那么我们就不在入库了
            await usersModel.find({ username }, function(err, res) {
                if (res[0].password === password) {
                    flag = true;
                    console.log('signin success');
                    return;
                }
            });
            return flag;
        }
    }
}


module.exports = {
    user: Mongo.user,
    position: Mongo.position
}